package family

import (
	"gitee.com/tang_q/gin-vue3-admin-api/global"
	"gitee.com/tang_q/gin-vue3-admin-api/model/dto"
	"gorm.io/gorm"
	"time"
)

type TangFamily struct {
	gorm.Model
	Name       string      `gorm:"type:varchar(50);comment:姓名" json:"name"`
	Gender     string      `gorm:"type:varchar(10);comment:性别" json:"gender"`
	Generation string      `gorm:"type:varchar(10);comment:辈份" json:"generation"`
	Country    string      `gorm:"type:varchar(20);comment:国籍" json:"country"`
	Region     string      `gorm:"type:varchar(20);comment:城市" json:"region"`
	Address    string      `gorm:"type:varchar(255);comment:详细地址" json:"address"`
	FatherID   uint        `gorm:"index:idx_parent,unique;comment:父亲ID" json:"father_id"` // 新增字段
	Father     *TangFamily `gorm:"foreignKey:FatherID;comment:父亲" json:"father"`
	MotherID   uint        `gorm:"index:idx_parent,unique;comment:母亲ID" json:"mother_id"` // 新增字段
	Mother     *TangFamily `gorm:"foreignKey:MotherID;comment:母亲" json:"mother"`
	SpouseID   uint        `gorm:"index:idx_spouse;comment:配偶ID" json:"spouse_id"` // 如果需要也可以为配偶增加外键
	Spouse     *TangFamily `gorm:"foreignKey:SpouseID;comment:配偶" json:"spouse"`
	Birthday   time.Time   `gorm:"comment:出生日期" json:"birthday"`
	Deathbed   time.Time   `gorm:"comment:死亡日期" json:"deathbed"`
}

func init() {
	err := global.DB.AutoMigrate(&TangFamily{})
	if err != nil {
		global.Logger.Error("创建表TangFamily失败", err)
		return
	}

}

func GetTangFamilyList(query dto.TangFamilyQueryDTO) (list []TangFamily, err error) {
	qs := global.DB.Model(&TangFamily{})
	if query.Name != "" {
		qs.Where("name = ?", query.Name)
	}
	if query.Gender != "" {
		qs.Where("gender = ?", query.Gender)
	}
	if query.Generation != "" {
		qs.Where("generation = ?", query.Generation)
	}
	err = qs.Preload("Father").Preload("Mother").Preload("Spouse").Find(&list).Error
	return
}
